package com.yhh;

import com.yhh.Entity.MyFile;
import com.yhh.myUtils.Serializations;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class Pipeline {
    public static Logger log = Server.log;
    public static ConcurrentHashMap<String,MyFile> pipeline;
    //"/servertmp/map.ser"
    public static final String path = System.getProperty("user.dir") + File.separatorChar + "servertmp" + File.separatorChar + "map.ser";

    public static File firstDirectory = new File(System.getProperty("user.dir") + File.separatorChar+ "servertmp");
    //"/servertmp/FTcahe
    public static File directory = new File(System.getProperty("user.dir") + File.separatorChar+ "servertmp" + File.separatorChar + "FTCache");

    public static void init() {
        if(!firstDirectory.exists()){
            if(!firstDirectory.mkdir()){
                log.error("主目录创建失败");
                return;
            }
        }
        if (!directory.exists()) {
            if(!directory.mkdir()){
                log.error("创建失败");
                return;
            }
        }
        File file = new File(path);
        if (file.exists()) {
            try {
                log.info("读取到map.txt文件");
                pipeline = (ConcurrentHashMap) Serializations.deserialize(path);
                if (pipeline.isEmpty()) {
                    log.info("map为空");
                }

            } catch (IOException | ClassNotFoundException e) {
                log.error("读取出现异常");
                log.error(e.getMessage());
                File mapSer = new File(path);
                mapSer.delete();
                log.info("map.ser已删除");
                pipeline = new ConcurrentHashMap<>();
            }
        } else {
            pipeline = new ConcurrentHashMap<>();
            log.info("pipeline已重置");
        }
        deleteUselessFile();
    }

    private static void deleteUselessFile() {
        log.info("删除无用文件");
        Set<String> _files = Arrays.stream(Objects.requireNonNull(directory.list())).collect(Collectors.toSet());
        pipeline.forEach((key, file) -> {
            if (_files.contains(file.getFilePath()) && file.getCounts() <= 0) {

            } else {
                _files.remove(file.getFilePath());
            }
        });
        //剩下的就是没有对应key的
        if (_files.isEmpty()) return;
        _files.stream().forEach(filename -> {
            File file = new File(directory.toString() + File.separatorChar + filename);

            try {
                String name = file.getName();
                file.delete();
                log.info("文件" + name + "被删除");
            } catch (Exception e) {
                log.error("删除失败");
            }
        });
    }

}
